package com.gui.util;

import com.gui.exceptions.RedisDataException;
import com.gui.exceptions.RedisEncodingException;

import java.io.UnsupportedEncodingException;

/**
 * Created by Gui on 2017/7/22.
 */
public class SafeEncoder {

    private static String CHARSET_NAME = "UTF-8";

    private SafeEncoder() {}

    public static byte[][] encodeMany(String... strs) {
        byte[][] many = new byte[strs.length][];
        for (int i = 0; i < strs.length; i ++) {
            many[i] = encode(strs[i]);
        }
        return many;
    }

    public static byte[] encode(String str) {
        try {
            if (str == null) {
                throw new RedisDataException("valve sent to redis cannot be null");
            }
            return str.getBytes(CHARSET_NAME);
        } catch (UnsupportedEncodingException e) {
            throw new RedisEncodingException(e);
        }
    }

    public static String decode(byte[] data) {
        return decode(data, 0, data.length);
    }

    public static String decode(byte[] data, int offset, int count) {
        try {
            return new String(data, offset, count, CHARSET_NAME);
        } catch (UnsupportedEncodingException e) {
            throw new RedisEncodingException(e);
        }
    }


}
